Page({
  data: {
    staffList: [],
    dateGroups: {},
    dates: [],
    currentDate: "",
    shiftTypeMap: {
      "早班": "morning",
      "中班": "afternoon",
      "晚班": "evening"
    },
    loading: true,
    error: null
  },

  onLoad() {
    this.fetchStaffSchedule();
  },

  fetchStaffSchedule() {
    this.setData({ loading: true, error: null });
    
    wx.request({
      url: 'http://localhost:8080/user/schedule-shift',
      success: (res) => {
        console.log('完整响应数据:', res); // 记录完整响应数据
        
        try {
          if (res.statusCode === 200) {
            // 检查响应数据结构
            if (!res.data || typeof res.data !== 'object') {
              throw new Error('响应数据格式不正确');
            }
            
            // 检查data字段是否存在
            if (!('data' in res.data)) {
              console.warn('响应中缺少data字段，尝试直接处理res.data');
              const transformed = this.transformData(res.data);
              this.setData({ ...transformed, loading: false });
              return;
            }
            
            // 处理res.data.data
            const transformed = this.transformData(res.data.data);
            this.setData({ ...transformed, loading: false });
          } else {
            throw new Error(`接口请求失败，状态码: ${res.statusCode}`);
          }
        } catch (err) {
          console.error('数据处理错误:', err);
          this.setData({ 
            error: err.message || '数据加载失败',
            loading: false
          });
        }
      },
      fail: (err) => {
        console.error('接口请求错误:', err);
        this.setData({ 
          error: `网络请求失败: ${err.errMsg}`,
          loading: false
        });
      }
    });
  },

  transformData(originalData) {
    console.log('原始数据内容:', JSON.stringify(originalData, null, 2)); // 记录原始数据内容
    
    
    if (!originalData) {
      console.warn('原始数据为空');
      return this.getDefaultData();
    }
    
    // 检查是否为数组
    if (!Array.isArray(originalData)) {
      console.warn('原始数据不是数组类型:', typeof originalData);
      
      // 尝试处理非数组数据
      if (typeof originalData === 'object' && originalData !== null) {
        // 检查是否为单个用户对象
        if ('name' in originalData && 'schedules' in originalData) {
          console.log('将单个用户对象转换为数组');
          return this.transformData([originalData]);
        }
        
        // 检查是否为日期映射对象
        if (Object.keys(originalData).some(key => key.includes('-'))) {
          console.log('尝试处理日期映射对象');
          return this.transformDateMap(originalData);
        }
      }
      
      return this.getDefaultData();
    }
    
    // 处理正常数组数据
    if (originalData.length === 0) {
      console.warn('排班数据为空数组');
      return this.getDefaultData();
    }

    const staffSet = new Set();
    const dateMap = {};
    const { shiftTypeMap } = this.data;

    originalData.forEach(user => {
      // 跳过无效用户数据
      if (!user || typeof user !== 'object') return;
      
      const userName = user.name || '未知用户';
      staffSet.add(userName);
      
      // 处理用户排班数据
      const schedules = user.schedules;
      if (!Array.isArray(schedules)) return;
      
      schedules.forEach(schedule => {
        // 跳过无效排班数据
        const date = schedule?.workTime;
        if (!date) return;
        
        // 初始化日期数据
        if (!dateMap[date]) {
          dateMap[date] = {
            weekday: schedule?.weekday || '',
            shifts: []
          };
        }
        
        // 处理班次数据
        const shifts = schedule?.shifts;
        if (Array.isArray(shifts) && shifts.length > 0) {
          shifts.forEach(shift => {
            if (shift) {
              const englishType = shiftTypeMap[shift.schedule] || 'default';
              dateMap[date].shifts.push({
                staff: userName,
                type: englishType,
                time: shift.scheduleTime || ''
              });
            }
          });
        }
      });
    });

    const dates = Object.keys(dateMap).sort();
    return {
      staffList: Array.from(staffSet),
      dateGroups: dateMap,
      dates,
      currentDate: dates[0] || ""
    };
  },
  
  // 处理日期映射格式的数据
  transformDateMap(dateMapData) {
    const staffSet = new Set();
    const dateMap = {};
    const { shiftTypeMap } = this.data;
    
    Object.entries(dateMapData).forEach(([date, data]) => {
      if (!data || !Array.isArray(data)) return;
      
      dateMap[date] = {
        weekday: data[0]?.weekday || '',
        shifts: []
      };
      
      data.forEach(item => {
        if (!item) return;
        
        const staff = item.staff || '未知员工';
        staffSet.add(staff);
        
        const shift = item.shift || {};
        const englishType = shiftTypeMap[shift.type] || 'default';
        
        dateMap[date].shifts.push({
          staff,
          type: englishType,
          time: shift.time || ''
        });
      });
    });
    
    const dates = Object.keys(dateMap).sort();
    return {
      staffList: Array.from(staffSet),
      dateGroups: dateMap,
      dates,
      currentDate: dates[0] || ""
    };
  },
  
  // 返回默认空数据
  getDefaultData() {
    return {
      staffList: [],
      dateGroups: {},
      dates: [],
      currentDate: ""
    };
  },

  onDateChange(e) {
    this.setData({ currentDate: e.currentTarget.dataset.date });
  }
});